package com.hmall.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.common.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Type;

@Configuration
@Slf4j
@ConditionalOnClass(RabbitTemplate.class)
public class MqConfig {

    @Bean
    public MessageConverter  messageConverter() {
        return new Jackson2JsonMessageConverter(){
          @Override
          public Object fromMessage(Message message) {
              Long userInfo = message.getMessageProperties().getHeader("user-info");
              log.info("当前解析的AMPQ消息的用户为："+userInfo);
              if (ObjectUtil.isNotEmpty(userInfo)){
                  UserContext.setUser(userInfo);
              }
              return super.fromMessage(message);
          }

          @Override
          public Message createMessage(Object objectToConvert, MessageProperties messageProperties, Type genericType){
              Long userInfo = UserContext.getUser();
              log.info("将用户信息存进AMPQ中");
              if (ObjectUtil.isNotEmpty(userInfo)){
                  messageProperties.setHeader("user-info",userInfo);
              }
              return super.createMessage(objectToConvert, messageProperties, genericType);
          }
        };

    }

}
